package com.zj.leetcode.hard.greed;

/**
 * @program: algorithm
 * @description: 分发糖果
 * 135 candy
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class Candy {
    public static void main(String[] args) {
        int[] ratings = {1,0,2};
        Solution solution = new Candy().new Solution();
        System.out.println(solution.candy(ratings));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int candy(int[] ratings) {
            if(ratings.length < 1){
                return 0;
            }
            if(ratings.length == 1){
                return 1;
            }

            int length = ratings.length;
            int[] nums = new int[length];
            for (int i = 1; i < length; i++) {
                if (ratings[i - 1] > ratings[i]) {
                    nums[i - 1] += 1;
                }
                nums[i] += 1;
            }


            for (int i = length - 2; i >= 0; i--) {
                if (ratings[i + 1] < ratings[i]) {
                    nums[i] = nums[i + 1] + 1;
                } else if (ratings[i + 1] >= ratings[i]) {
                    nums[i] = 1;
                }
            }

            int count = 0;
            for (int i = 0; i < nums.length; i++) {
                count += nums[i];
            }

            return count;
        }
    }

    class Solution1 {
        public int candy(int[] ratings) {
            int n = ratings.length;
            int ret = 1;
            int inc = 1, dec = 0, pre = 1;
            for (int i = 1; i < n; i++) {
                if (ratings[i] >= ratings[i - 1]) {
                    dec = 0;
                    pre = ratings[i] == ratings[i - 1] ? 1 : pre + 1;
                    ret += pre;
                    inc = pre;
                } else {
                    dec++;
                    if (dec == inc) {
                        dec++;
                    }
                    ret += dec;
                    pre = 1;
                }
            }
            return ret;
        }
    }

//leetcode submit region end(Prohibit modification and deletion)

}